package com.fit.pages.organization;

import java.util.List;

import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.PropertyAccess;

import com.fit.entities.ContactPerson;
import com.fit.entities.Organization;
import com.fit.model.gsm.GenericSelectModel;
import com.fit.pages.Confirmation;
import com.fit.dao.contactPerson.ContactPersonDAO;
import com.fit.dao.organization.OrganizationDAO;

public class AddOrganization {

	@Property
	private List<Organization> Organizations;


	@Property
	private Organization organization;

	@Persist
	private String msg;


	@Inject
	private OrganizationDAO organizationDAO;

	@InjectPage
	private Confirmation confirmation;
	
	@Inject
	private PropertyAccess access;
	
	@Inject
	private ContactPersonDAO contactPersonDAO;

	@InjectPage
	private AddOrganization addOrganization;
	
	@Property
	private ContactPerson contactPerson;

	private GenericSelectModel<ContactPerson> contactPersons;
 
	public GenericSelectModel<ContactPerson> getContactPersons() {
		contactPersons = new GenericSelectModel<ContactPerson>(
				contactPersonDAO.findAll(), ContactPerson.class, "nameSurname", "id",
				access);
		return contactPersons;
	}
	

	void onActivate() {
		Organizations = organizationDAO.findAll();
		organization=null;		
	}


	Object onSuccess() {
		confirmation.setError("");
		confirmation.setConfirmation("");
		Organization temp = organizationDAO.findByID(organization.getId());

		if (temp == null) {
			organization.setContactPerson(contactPerson);
			if (organizationDAO.save(organization)) {				
				msg = "Organization successfully added!";
				organization=null;
				return addOrganization;
			}
			confirmation.setConfirmation("Language is null!");
			return confirmation;
		}

		confirmation.setError("Language with " + organization.getId()
				+ " ID already exists!");

		return confirmation;
	}


	@OnEvent(component = "deleteLink")
	Object onDeleteLink(Long id) {
		try {
			organizationDAO.deleteByID(id);
			msg = "Organization successfully deleted!";
			return null;
		} catch (Exception e) {
			confirmation
					.setConfirmation("Greska prilikom brisanja zapisa korisnika! ");
			return confirmation;
		}
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}


	

}
